import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_branch_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/add_user_address_page.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'create_user_branch_vied_model.dart';

class AddAndRemoveUserBranchPage extends StatefulWidget {

  final String fuid;
  final String fid;
  final bool createEdit;
  final List<CompanyBranchListInfoBean> listBranchBean;

  const AddAndRemoveUserBranchPage({Key key, this.fuid, this.fid, this.createEdit, this.listBranchBean}) : super(key: key);

  @override
  _AddAndRemoveUserBranchPageState createState() => _AddAndRemoveUserBranchPageState();

  static Future<AddRemoveAddressData> navigatorPush(
      BuildContext context,List<CompanyBranchListInfoBean> listBranchBean,
      String fuid, String fid,
      {bool createEdit}) {
    return RouterUtils.routeForFutureResult<AddRemoveAddressData>(
      context,
      AddAndRemoveUserBranchPage(
          fuid:fuid,
          fid:fid,
          createEdit:createEdit,
          listBranchBean:listBranchBean
      ),
    );
  }
}

class _AddAndRemoveUserBranchPageState extends BasePagerState<CompanyBranchListInfoBean, AddAndRemoveUserBranchPage> {
  CreateUserBranchViewModel viewModel;
  List<CompanyBranchListInfoBean> showList = [];
  final AddRemoveAddressData _addRemoveAddressData = AddRemoveAddressData();
  String locationGps;

  @override
  void initState() {
    super.initState();
    viewModel = CreateUserBranchViewModel(this,"");
    showList = widget?.listBranchBean;

    VgLocation().requestSingleLocation((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        print("刷脸地址最新gps:" + value);
        setState(() {locationGps = value;});
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        RouterUtils.pop(context, result: _addRemoveAddressData);
        return true;
      },
      child: CustomAnnotatedRegion(
        Scaffold(
          backgroundColor: Color(0xFF191E31),
          body: CommonPackUpKeyboardWidget(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                _toTopBarWidget(),
                if((showList?.length ?? 0) != 0)
                  Expanded(
                    child: _toPullRefreshWidget(),
                  ),
                // _addAddress()
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "刷脸地址",
      navFunction:(){
          RouterUtils.pop(context, result: _addRemoveAddressData);
      },
      rightWidget: GestureDetector(
          onTap: (){
            AddUserAddressPage.navigatorPush(context, showList, locationGps,
                fuid: widget?.fuid, fid:widget?.fid, createEdit: widget?.createEdit)
                .then((value) {
              if(value==null){
                return;
              }
              setState(() {
                if(widget?.fuid != "" && (widget?.createEdit ?? false)){
                  value?.editSelected = true;
                }
                showList?.add(value);
                _addRemoveAddressData?.add(value);
              });
            });
            setState(() { });
          },
          child: Text(
            "+新增",
            style: TextStyle(
                fontSize: 14,
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
          )),
    );
  }

  Widget _toPullRefreshWidget() {
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: ListView.separated(
          itemCount: showList?.length ?? 0,
          padding: const EdgeInsets.all(0),
          physics: BouncingScrollPhysics(),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return _toListItemWidget(context, index, showList[index]);
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(height: 0.1);
          }),
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, CompanyBranchListInfoBean itemBean) {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Column(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "${itemBean?.branchname}",
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    ),
                  ),
                ),
                SizedBox(height: 2),
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    AddressAboutUtils.getBranchSplicing(itemBean) ?? "",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 12,
                      color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // Spacer(),
          GestureDetector(
            onTap: () async {
              itemBean?.selected = false;
              if(!(widget?.createEdit ?? false)){
                viewModel.setUserBranch(widget?.fuid, widget?.fid, "", itemBean?.cbid);
              }
              showList?.remove(itemBean);
              _addRemoveAddressData.remove(itemBean);
              setState(() { });
            },
            child: Visibility(
              visible:(showList?.length ?? 0) !=1 || (showList?.length ?? 0) >1,
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Image.asset(
                  "images/icon_close_volume_dialog.png",
                  width: 11,
                  height: 11,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class AddRemoveAddressData {
  List<CompanyBranchListInfoBean> addList = [];
  List<CompanyBranchListInfoBean> removeList = [];

  void add(CompanyBranchListInfoBean item) {
    if(removeList != null && removeList.contains(item)){
      removeList.remove(item);
      return;
    }
    addList.add(item);
  }

  void remove(CompanyBranchListInfoBean item) {
    if(addList != null && addList.contains(item)){
      addList.remove(item);
      return;
    }
    removeList.add(item);
  }
}
